package com.zzyl.alarm;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description DeviceAlarmProcessor
 * @Author fy
 * @Date 2025-05-24  15:36
 */
@Component
public class DeviceAlertProcessor {
    @Autowired
    private StringRedisTemplate  redisTemplate;
    @Autowired
    private AlertRuleMapper  alertRuleMapper;
    @Autowired
    private DeviceMapper  deviceMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;
    //定时任务，每分钟触发1次
    @Scheduled(cron = "0 * * * * ?")
    public void AlertRuleCheckTask(){
        //1.查询所有规则
        List<AlertRule> allRules = alertRuleMapper.queryAllRules();
        //2.判断规则是否为空
        if(ObjectUtil.isEmpty(allRules)){
            //为空则结束
            return;
        }
        //3.非空，查询所有设备最新上报的数据，从redis里面查找最新的数据
        Map<Object,Object> deviceDataMap = redisTemplate.opsForHash().entries(CacheConstants.DEVICE_LASTDATA_CACHE_KEY);
        //4.判断redis中的数据是否为空
        if(ObjectUtil.isEmpty(deviceDataMap)){
            //为空则结束
            return;
        }
        //5.非空,对数据格式标准化处理，处理每条设备数据
        deviceDataMap.forEach((key,value) ->{
            String iotId = (String) key;
            String deviceDataStr = (String) value;
            if(ObjectUtil.isNotEmpty(deviceDataStr)){
                //5.1将上报的数据转成List<DeviceDataVo>
                List<DeviceDataVo> deviceDataVos = JSONUtil.toList(deviceDataStr,DeviceDataVo.class);
                //5.2 遍历每条设备数据并进行规则校验
                deviceDataVos.forEach(dataVo ->processDeviceData(dataVo,allRules));
            }
        });
    }

    private List<AlertRule> processDeviceData(DeviceDataVo dataVo, List<AlertRule> allRules) {
        //5.3 判断设备上报时间是否大于1分钟
        if (isDataOlderThanOneMinute(dataVo)){
            //5.3.1 是则结束
            return null;
        }

        //5.4 否，将全部设备的报警规则和本设备的报警规则合并
        List<AlertRule> mergedRules = mergeRules(allRules,dataVo);
        //5.5 判断合并后的规则集合是否为空
        if (ObjectUtil.isEmpty(mergedRules)){
            //是 则结束
            return null;
        }
        //6.否，通过数据报警处理器对数据作报警
        //6.1 首先遍历每一条规则
        for (AlertRule rule : mergedRules){
            processAlertRule(dataVo,rule);
        }
        return mergedRules;
    }



    //判断设备上报时间是否大于1分钟
    private boolean isDataOlderThanOneMinute(DeviceDataVo dataVo) {
        return ChronoUnit.MINUTES.between(dataVo.getAlarmTime(), LocalDateTime.now())> 1;
    }
    //将全部设备的报警规则和本设备的报警规则合并
    private List<AlertRule> mergeRules(List<AlertRule> allRules, DeviceDataVo dataVo) {
        List<AlertRule> mergedRules = allRules.stream()
                .filter(rule -> "-1".equals(rule.getIotId()) || rule.getIotId().equals(dataVo.getIotId()))
                .collect(Collectors.toList());
        return mergedRules;
    }
    //通过数据报警处理器对数据作报警
    private void processAlertRule(DeviceDataVo dataVo, AlertRule rule) {
        //6.2 判断是否在生效时间内
        if (!isInAlertEffectivePeriod(rule)){
            //否则结束
            return;
        }
        //6.3 判断数据是否达到阈值
        if (!isDataExceedsThreshold(dataVo,rule)){
            //未达到，删除redis报警数
            redisTemplate.delete(getAlarmCountKey(dataVo.getIotId(),rule.getIotId()));
            //结束
            return;
        }
        //7.在redis中查询沉默周期（设置定时删除超过沉默周期的数据）
        // String silencePeriod = redisTemplate.opsForValue().get(getSilencePeriodKey(dataVo.getIotId(),rule.getIotId()));
        String silenceKey = getSilencePeriodKey(dataVo.getIotId(), rule.getIotId());
        if (redisTemplate.hasKey(silenceKey)) {
            return;
        }
        //7.1判断沉默周期内数据是否为空
        // if (silenceKey != null){
        //     //非空，表示报警时间没有到
        //     return;
        //
        // }
        //8.空，说明已超过沉默时间，查询redis中已报警次数
        String countKey = getAlarmCountKey(dataVo.getIotId(),rule.getIotId());
        String countStr = redisTemplate.opsForValue().get(countKey);
        Integer alarmCount = countStr != null ? Integer.parseInt(countStr) : 0;
        //9. 计算当前报警数，
        int currentAlarmCount = alarmCount + 1;
        //判断报警次数是否等于持续周期
        if (currentAlarmCount < rule.getDuration()){
            //不等，redis报警数+1
            redisTemplate.opsForValue().increment(countKey);
            //结束
            return;

        }
        //10.删除redis报警数
        redisTemplate.delete(countKey);
        //11.添加redis沉默周期
        redisTemplate.opsForValue().set(silenceKey,"1",rule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        List<AlertData> alertDataList = buildAlertDataList(dataVo,rule);
        //12.判断是否是老人异常数据
        if (rule.getAlertDataType() == 0){
            handleElderAbnormal(dataVo,alertDataList);
        }else{
            //13.非老人异常数据,则是设备异常数据，通知维修员
            handleDeviceAbnormal(alertDataList);
        }
    }
    //判断数据是否达到阈值
    private boolean isDataExceedsThreshold(DeviceDataVo dataVo, AlertRule rule) {
        return false;
    }
    private List<AlertData> buildAlertDataList(DeviceDataVo dataVo, AlertRule rule) {
        AlertData alertData = new AlertData();
        alertData.setIotId(dataVo.getIotId());
        alertData.setDeviceName(dataVo.getDeviceName());
        alertData.setNickname(dataVo.getNickname());
        alertData.setProductKey(dataVo.getProductKey());
        alertData.setProductName(dataVo.getProductName());
        alertData.setFunctionId(dataVo.getFunctionId());
        alertData.setAccessLocation(dataVo.getAccessLocation());
        alertData.setLocationType(dataVo.getLocationType());
        alertData.setPhysicalLocationType(dataVo.getPhysicalLocationType());
        alertData.setDeviceDescription(dataVo.getDeviceDescription());
        alertData.setDataValue(dataVo.getDataValue());
        alertData.setAlertRuleId(rule.getId());
        alertData.setAlertReason(rule.getFunctionName()+rule.getOperator()+rule.getValue()+rule.getDuration()+rule.getAlertEffectivePeriod());
        alertData.setType(dataVo.getLocationType());
        alertData.setStatus(0);
        return Collections.singletonList(alertData);
    }
    private String getAlarmCountKey(String deviceIotId, String ruleIotId) {
        return String.format(CacheConstants.DEVICE_ALARM_COUNT_KEY, deviceIotId, ruleIotId);
    }

    private String getSilencePeriodKey(String deviceIotId, String ruleIotId) {
        return String.format(CacheConstants.DEVICE_ALARM_SILENCE_PERIOD_KEY, deviceIotId, ruleIotId);
    }


    //12.判断是否是老人异常数据
    private void handleElderAbnormal(DeviceDataVo data, List<AlertData> list) {
        //12.1 是，再判断是否是固定设备异常
        if (data.getLocationType().equals(1)){
            //12.1.1 是通过床位通知老人护理员
            deviceMapper.selectNursingIdsWithBed(data.getIotId());
            //12.1.2 通知超级管理员
            //12.1.3 批量保存报警信息
            alertDataMapper.batchInsert(list);
            return;
            //结束
        }
        //12.2 否，通过老人随身设备通知护理员
        if (data.getLocationType().equals(0)){
            deviceMapper.selectNursingIdsWithElder(data.getIotId());
            //12.2.1.通知超级管理员
            //12.2.2批量保存报警信息
            alertDataMapper.batchInsert(list);
            //结束

        }
    }
    //13.非老人异常数据,则是设备异常数据，通知维修员
    private void handleDeviceAbnormal(List<AlertData> list) {
        //13.1 通过设备通知维修员
        userRoleMapper.selectByRoleName("维修工");
        //通知超级管理员
        //批量保存报警数据
        alertDataMapper.batchInsert(list);

        //结束
    }

    //判断规则是否再生效时间范围内
    private boolean isInAlertEffectivePeriod(AlertRule rule){
        if (ObjectUtil.isEmpty(rule.getAlertEffectivePeriod())) {
            return false; // 如果生效时间为空，返回 false
        }

        // 获取当前时间
        LocalTime now = LocalTime.now();

        // 解析生效时间区间
        String[] parts = rule.getAlertEffectivePeriod().split("~");
        if (parts.length != 2) {
            return false; // 格式错误，返回 false
        }

        LocalTime startTime = LocalTime.parse(parts[0]);
        LocalTime endTime = LocalTime.parse(parts[1]);

        // 处理跨天的情况（如 "22:00:00~08:00:00"）
        if (startTime.isAfter(endTime)) {
            // 当前时间在 startTime 之后且在 endTime 之前（跨天情况）
            return now.isAfter(startTime) || now.isBefore(endTime);
        } else {
            // 当前时间在 startTime 和 endTime 之间（正常情况）
            return now.isAfter(startTime) && now.isBefore(endTime);
        }
    }
}
